<?php
define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
require_once(ROOT_PATH . '/' . ADMIN_PATH . '/includes/lib_goods.php');

$exc = new exchange($ecs->table("goods_collection"), $db, 'id','');

$action = $_REQUEST['act']?$_REQUEST['act']:'list';

if ($action == 'list')
{
	admin_priv('goods_group');
	
	$list = get_collection_list();
	
// 	print_r($filter);
	$smarty->assign('collection', $list['list']);
	assign_query_info();
	$smarty->assign('ur_here',          $_LANG['goods_group']);
	$smarty->assign('action_link',      array('text' => $_LANG['add_group'], 'href' => 'goods_group.php?act=add'));
	$smarty->assign('filter', $list['filter']);
	$smarty->assign('record_count',     $list['record_count']);
	$smarty->assign('page_count',      $list['page_count']);
	$smarty->assign('full_page', 1);
	$smarty->assign('lang',         $_LANG);
	$smarty->display('goods_group.htm');
}

elseif ($_REQUEST['act'] == 'query')
{
	$list = get_collection_list();

	$smarty->assign('collection',    $list['list']);
	$smarty->assign('filter',       $list['filter']);
	$smarty->assign('record_count', $list['record_count']);
	$smarty->assign('page_count',   $list['page_count']);

	make_json_result($smarty->fetch('goods_group.htm'), '',
			array('filter' => $list['filter'], 'page_count' => $list['page_count']));
}

elseif ($action == 'remove')
{
	$collect_id = intval($_REQUEST['id']);
	$collection = get_goods_collection($collect_id);
	if (!empty($collection['goods_list']))
	{
		$sql = "UPDATE ".$ecs->table('goods')." SET collection_id=0 WHERE goods_id IN($collection[goods_list])";
		$db->query($sql);
	}
	
	if ($exc->drop($collect_id))
	{
		
		clear_cache_files();
	}
	$url = 'goods_group.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);
	
	ecs_header("Location: $url\n");

	exit;
}
elseif ($action == 'add')
{
	assign_query_info();
	$smarty->assign('ur_here',          $_LANG['add_group']);
	$smarty->assign('action_link',      array('text' => $_LANG['goods_group'], 'href' => 'goods_group.php?act=list'));
	$smarty->assign('form_act',    'insert');
	$smarty->assign('goods_type_list', goods_type_list(''));
	$smarty->assign('goods_attr_list', build_collattr_html());
	$smarty->assign('goods_list_html', build_goods_html('','',''));
	$smarty->display('goods_group_info.htm');
}
elseif ($action == 'insert' || $action == 'update')
{
	if (empty($_POST['collect_name']))
	{
		sys_msg($_LANG['group_name_not_null'], 1);
		exit;
	}
	$goods_collect['name']   = sub_str(trim($_POST['collect_name']), 60);
// 	$goods_collect['enabled']    = intval($_POST['enabled']);
	$goods_collect['goods_list'] = isset($_POST['goods'])?implode(',', $_POST['goods']):'';
	$goods_collect['goods_type'] = $_POST['goods_type']?$_POST['goods_type']:0;
	$goods_collect['goods_attr'] = $_POST['goods_attr']?$_POST['goods_attr']:0;
	$goods_collect['last_update'] = time();
// 	print_r($goods_collect);

	
	if ($action == 'insert')
	{
		if ($db->autoExecute($ecs->table('goods_collection'), $goods_collect,'INSERT') !== false)
		{
			if (!empty($goods_collect['goods_list']))
			{
				$collection_id = $db->insert_id();
				$sql = "UPDATE ".$ecs->table('goods')." SET collection_id='$collection_id' WHERE goods_id IN($goods_collect[goods_list])";
				$db->query($sql);
			}
			/* 清空缓存 */
			clear_cache_files();
			$links = array(array('href' => 'goods_group.php?act=list', 'text' => $_LANG['back_list']));
			sys_msg('添加成功', 0, $links);
		}
		else
		{
			sys_msg('添加失败', 1);
		}
	}
	else 
	{
		$collection = get_goods_collection($_POST[collect_id]);
		if(!empty($collection['goods_list'])){
			$sql = "UPDATE ".$ecs->table('goods')." SET collection_id=0 WHERE goods_id IN($collection[goods_list])";
			$db->query($sql);
		}
		
		
		if ($db->autoExecute($ecs->table('goods_collection'), $goods_collect,'UPDATE',"id = '$_POST[collect_id]'") !== false)
		{
			if (!empty($goods_collect['goods_list']))
			{
				$sql = "UPDATE ".$ecs->table('goods')." SET collection_id='$_POST[collect_id]' WHERE goods_id IN($goods_collect[goods_list])";
				$db->query($sql);
			}
			/* 清空缓存 */
			clear_cache_files();
			$links = array(array('href' => 'goods_group.php?act=list', 'text' => $_LANG['back_list']));
			sys_msg('修改成功', 0, $links);
		}
		else
		{
			sys_msg('修改失败', 1);
		}
	}
	
}
elseif ($action == 'edit')
{
	$sql = ' SELECT * FROM '.$ecs->table('goods_collection').' WHERE id="'.$_GET['collect_id'].'"';
	$coll = $db->getRow($sql);
	
	assign_query_info();
	$smarty->assign('ur_here',          '编辑商品组');
	$smarty->assign('action_link',      array('text' => $_LANG['goods_group'], 'href' => 'goods_group.php?act=list'));
	$smarty->assign('form_act',    'update');
	$smarty->assign('goods_type_list', goods_type_list($coll['goods_type']));
	$smarty->assign('goods_attr_list', build_collattr_html($coll['goods_type'],$coll['goods_attr']));
	$smarty->assign('goods_list_html', build_goods_html($coll['goods_type'], $coll['goods_list'],$coll['goods_attr']));
	$smarty->assign('collect', $coll);
	$smarty->display('goods_group_info.htm');
}

elseif ($action == 'get_attr_list')
{
	$goods_type = empty($_GET['goods_type']) ? 0 : intval($_GET['goods_type']);

	$content    = build_collattr_html($goods_type);

	make_json_result($content);
}

elseif ($action == 'get_goods_list')
{
	include_once(ROOT_PATH .'includes/cls_json.php');
	$json = new JSON();
	$result=array('error'=>0,'content'=>'');
	
	$goods_type=intval($_GET['goods_type']);
	$goods_attr=intval($_GET['goods_attr']);
	$collect_id = intval($_GET['collect_id']);
	$collection = get_goods_collection($collect_id);
	$goods_list = $collection['goods_list'];
	
	$str=build_goods_html($goods_type,$goods_list,$goods_attr);
	
	$result['content']=$str;
	die($json->encode($result));

}

function build_collattr_html( $goods_type=0,$goods_attr=0 )
{
	$html = '<option value="0">请选择商品属性</option>';
	if ($goods_type>0)
	{
		$sql = "SELECT * FROM ".$GLOBALS['ecs']->table('attribute')." WHERE cat_id='$goods_type'";
		$res = $GLOBALS['db']->getAll($sql);
		
		foreach ($res as $k=>$v)
		{
			if ($v['attr_id']==$goods_attr)
			{
				$select = 'selected="true"';
			}
			else
			{
				$select = '';
			}
			$html .= '<option value="'.$v['attr_id'].'" '.$select.'>'.$v['attr_name'].'</option>';
		}
	}
	return $html;
}


function build_goods_html($goods_type, $goods_list = '', $goods_attr)
{
	$goods_list=explode(',', $goods_list);
	$sql=' SELECT g.goods_name,g.goods_id,ga.attr_value,g.collection_id FROM '.$GLOBALS['ecs']->table('goods').' as g'.
			' LEFT JOIN '.$GLOBALS['ecs']->table('goods_attr').' as ga ON ga.goods_id=g.goods_id'.
			' LEFT JOIN '.$GLOBALS['ecs']->table('attribute').' as a ON a.attr_id=ga.attr_id'.
			' WHERE a.attr_type=1 AND g.goods_type ="'.$goods_type.'" AND ga.attr_id="'.$goods_attr.'" AND g.is_delete=0 AND g.is_on_sale=1 ORDER BY g.goods_id DESC';
	$res=$GLOBALS['db']->getAll($sql);
	// print_r();
	$str='';
	$goods=array();
	if($res)
	{
		foreach($res as $k=>$v)
		{
			$goods[$v['goods_id']]['checked']='';
			$goods[$v['goods_id']]['disabled']='';
			if(in_array($v['goods_id'],$goods_list))
			{
				$goods[$v['goods_id']]['checked']='checked';
			}
			else
			{
				
				if ($v['collection_id']>0)
				{
					$goods[$v['goods_id']]['checked']='checked';
					$goods[$v['goods_id']]['disabled']='disabled';
				}
					
			}
			
			$goods[$v['goods_id']]['attr'].=' '.$v['attr_value'];
			$goods[$v['goods_id']]['goods_name']=$v['goods_name'];
			$goods[$v['goods_id']]['goods_id']=$v['goods_id'];
		}
		foreach($goods as $k=>$v)
		{
			$str.='<div>
					<input '.$v['checked'].' '.$v['disabled'].' type="checkbox" id="cb_'.$k.'" name="goods[]" value="'.$v['goods_id'].'" autocomplete="off">
					<label for="cb_'.$k.'">'.$v['goods_id'].'.'.$v['goods_name'].'['.$v['attr'].']</label>
				  </div>';
		}
	}
	return $str;
// 	return $sql;
}

function get_goods_collection( $collection_id = 0 )
{
	$result = array();
	if ($collection_id>0)
	{
		$sql = 'SELECT * FROM '.$GLOBALS['ecs']->table('goods_collection').' WHERE id = "'.$collection_id.'"';
		$result = $GLOBALS['db']->getRow($sql);
		$result['goods'] = explode(',', $result['goods_list']);
	}
	return $result;
}

function get_collection_list()
{
	$sql = 'SELECT COUNT(*) FROM '.$GLOBALS['ecs']->table('goods_collection').' AS gc'.
			' LEFT JOIN '.$GLOBALS['ecs']->table('goods_type').' AS gt ON gt.cat_id=gc.goods_type '.
			' ORDER BY gc.id DESC ';
	
	$filter['record_count'] = $GLOBALS['db']->getOne($sql);
	
	/* 分页大小 */
	$filter = page_and_size($filter);
	
	$sql = 'SELECT gc.*,gt.cat_name as type FROM '.$GLOBALS['ecs']->table('goods_collection').' AS gc'.
			' LEFT JOIN '.$GLOBALS['ecs']->table('goods_type').' AS gt ON gt.cat_id=gc.goods_type '.
			' ORDER BY gc.id DESC LIMIT '. $filter['start'] .','. $filter['page_size'];
	$res = $GLOBALS['db']->getAll($sql);
	
	foreach ($res as $k=>$collection)
	{
		if ($collection['goods_list'])
		{
				
			$sql = ' SELECT goods_name FROM '.$GLOBALS['ecs']->table('goods').' WHERE goods_id IN ('.$collection['goods_list'].')';
			$goods_arr = $GLOBALS['db']->getCol($sql);
			$res[$k]['goods'] = implode(',', $goods_arr);
		}
	}
	
	$result = array('list'=>$res, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
	return $result;
}